#!/bin/bash

PROGDIR=`(cd "$(dirname "$0")"; pwd)`
PROGNAME=dcs
CMD="nohup java -jar -Dloader.path=. $PROGDIR/bdp-$PROGNAME-0.0.1-SNAPSHOT.jar >/dev/null 2>&1 &"
CMD_CNT="ps -ef | grep $PROGNAME | grep -v grep | wc -l"
CHECK_ALIVE_PID=${PROGDIR}/checkalive.stat
CHECK_ALIVE_LOG=${PROGDIR}/checkalive.log

Usage(){
    echo "Usage: $0 [start|stop|restart|stat|checkalive]"
    echo "     start                   : start $PROGNAME"
    echo "     stop                    : stop $PROGNAME and automatically stop checkalive"
    echo "     restart                 : restart $PROGNAME"
    echo "     stat                    : view the status of the $PROGNAME"
    echo "     checkalive              : start checkalive and $PROGNAME"
    echo ""
    exit 1
}

Stat(){
    cnt=$(eval $CMD_CNT)
    if (( cnt >= 1 ))
    then
        echo "$PROGNAME is running."
    else
        echo "$PROGNAME process does not exist."
    fi
}

Start(){
    cnt=$(eval $CMD_CNT)
    if (( cnt >= 1 ))
    then
        echo "$PROGNAME is already running."
        exit 0
    fi

    cd $PROGDIR
    echo $CMD >> $CHECK_ALIVE_LOG
    $CMD &
    echo "`date`, start $PROGNAME " >> $CHECK_ALIVE_LOG
}

Stop(){
    StopCheckAlive

    cnt=$(eval $CMD_CNT)
    if (( cnt < 1 ))
    then
        echo "$PROGNAME is not exist"
        return
    fi

    pid=$(ps -ef | grep $PROGNAME | grep -v grep | awk '{print $2}')
    kill $pid

    echo "$PROGNAME is stoped."
    echo "`date`, stop $PROGNAME " >> $CHECK_ALIVE_LOG
}

Restart(){
    Stop
    Start
}

StopCheckAlive(){
    cnt=`ps -ef | grep service.sh | grep -E "start|checkalive"  | grep -v stop | grep -v grep | wc -l`
    if (( cnt >= 1 ))
    then
        pid=$(ps -ef | grep service.sh | grep -E "start|checkalive" | grep -v stop | grep -v grep | awk '{print $2}')
        kill $pid
        echo "`date`, stop checkAlive"  >> $CHECK_ALIVE_LOG
    fi
    rm -rf $CHECK_ALIVE_PID
}

IsCheckAliveRunning(){
    if [ -f "$CHECK_ALIVE_PID" ]; then
        echo "checkAlive is already running."
        exit 0
    else
        echo "start checkAlive"
        echo "`date`, start checkAlive"  >>  $CHECK_ALIVE_LOG
        #set checkAlive running
        echo "checkalive is running" > $CHECK_ALIVE_PID
    fi
}

CheckAlive(){
    IsCheckAliveRunning

    #exec checkAlive
    while (( 1 ))
    do
        cnt=$(eval $CMD_CNT)
        if (( cnt < 1 ))
        then
            cd $PROGDIR;
            echo $CMD >> $CHECK_ALIVE_LOG
            $CMD &
            echo "`date`, checkalive detected the program exit, restart $PROGNAME" >> $CHECK_ALIVE_LOG
        fi
        sleep 2
    done

    echo "`date` checkAlive exit." >> $CHECK_ALIVE_LOG
}

case $1 in
    start)
        Start
    ;;
    stop)
        Stop
    ;;
    stat)
        Stat
    ;;
    restart)
        Restart
    ;;
    checkalive)
        CheckAlive &
    ;;
    *)
        Usage
    ;;
esac

